#include <stdio.h>
#include <time.h>
#include <sys/time.h>
#include <sys/resource.h>

int main (int argc, char *argv[]){ 

  //variables
  //scan time in microseconds
  int scan = atoi(argv[1]);
  //seed rand
  srand (time(NULL));
  //get cycle time
  float cycle = scan*(rand()%(100+atoi(argv[2])))/100;
  //flag to show that a scan has finished
  int end = 0;
  //infinite counter to dont let the process sleep
  int counter;
  //scan start and actual time
  struct timeval scaninit, scanactual;
  // variables used to calculate the elapsed time
  long seconds, useconds, elapsed;

  //main loop (inifinite?)
  printf("+----------+------------+------------+------------+------------+\n");
  printf("|  Status  |    Scan    |   Cycle    |  Elapsed   |  Priority  |\n");
  printf("+----------+------------+------------+------------+------------+\n");
  while (1) {
    gettimeofday(&scaninit, NULL);
    while (!end){
      gettimeofday(&scanactual, NULL);
      seconds = scanactual.tv_sec - scaninit.tv_sec;
      useconds = scanactual.tv_usec - scaninit.tv_usec;
      elapsed = ((seconds)*1000000 + useconds); //check
        if (elapsed < cycle) { 
          counter++;
        } else {
          if (elapsed > scan) { 
            printf("| Overrun  | %*d | %*f | %*ld | %*d |\n", 10, scan, 10, cycle, 10, elapsed, 10, getpriority(PRIO_PROCESS,0));
          } else {
            printf("| Finished | %*d | %*f | %*ld | %*d |\n", 10, scan, 10, cycle, 10, elapsed, 10, getpriority(PRIO_PROCESS,0));
          }
        printf("+----------+------------+------------+------------+------------+\n");
        end = 1;
        }
    }
  cycle = scan*(rand()%(100+atoi(argv[2])))/100.0;
  end = 0;
  }
}
